import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import menuIcons from './menuIcons.json'

import router from "../router";
import { routesDefault } from "@/router"
import { getMenus } from "@/api/rights"


export default new Vuex.Store({
    state: {
        opened: true,
        userInfo: sessionStorage.getItem('cms_token') ? JSON.parse(sessionStorage.getItem('cms_token')) : null,
        cms_token: sessionStorage.getItem('cms_token') ? sessionStorage.getItem('cms_token') : null,
        menuIcons: menuIcons,
        menuList: [],
        localRouter: sessionStorage.getItem('localRouter') ? JSON.parse(sessionStorage.getItem('localRouter')) : []
    },
    getters: {
        token(state) {
            return state.cms_token
        }
    },
    mutations: {
        SET_OPENED(state) {
            state.opened = !state.opened
        },
        SET_USERINFO(state, userInfo) {
            state.userInfo = userInfo
            state.cms_token = userInfo.token

            sessionStorage.setItem('cms_token', state.cms_token)
            sessionStorage.setItem('userInfo', JSON.stringify(userInfo))

        },
        setMenuList(state, list) {
            state.menuList = list
        },
        setlocalRouter(state, list) {
            state.localRouter = list
            sessionStorage.setItem('localRouter', JSON.stringify(list))
        }
    },
    actions: {
        async getMenuList(store) {
            console.log('actions:', this);
            const res = await getMenus()
            console.log("左侧菜单数据", res);

            store.commit('setMenuList', res.data)

            //动态路由 数据组装
            let homeRoute = routesDefault[1];
            console.log(homeRoute);
            store.state.menuList.forEach((item) => {
                item.children.forEach((subItem) => {
                    const route = {
                        name: subItem.path,
                        path: "/" + subItem.path,
                        fname: item.path,
                        component: () =>
                            import (`@/views/${item.path}/${subItem.path}.vue`),
                    };
                    homeRoute.children.push(route);
                });
            });
            router.addRoute(homeRoute)
            store.commit('setlocalRouter', homeRoute)
            console.log(router.getRoutes());
        }
    },
    modules: {},
});